<template>
  <div class="content-body">
    <div class="header">
      <!-- 左侧按钮 -->
      <div class="header-left">
        <el-button type="primary" size="small" @click="goSysTanks">
          管理后台
        </el-button>
      </div>

      <!-- 中间标题 -->
      <div class="header-title">
        <span>水质情况实时监测预警系统</span>
      </div>

      <!-- <div class="header-time">
        <span>{{ time }}</span>
      </div> -->
      <!-- 右侧时间 + AI按钮 -->
      <div class="header-time">
        <button class="ai-btn" @click="aiOpen = !aiOpen" title="AI 助手">
          <!-- 简单机器人图标，你也可换成图片 -->
          <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
            <path d="M12 2a1 1 0 011 1v1h2a2 2 0 012 2v2h1a2 2 0 012 2v5a3 3 0 01-3 3h-1.18a3 3 0 01-2.82 2h-4a3 3 0 01-3-3V10a2 2 0 012-2h1V6a2 2 0 012-2h2V3a1 1 0 011-1h2zM7 11.5a1.5 1.5 0 103 0 1.5 1.5 0 00-3 0zm7 0a1.5 1.5 0 103 0 1.5 1.5 0 00-3 0zM9 17h6a1 1 0 100-2H9a1 1 0 100 2z"/>
          </svg>
        </button>
        <span>{{ time }}</span>
      </div>
    </div>

    <!-- 内容主体 -->
  <div class="main-wrap">
    <div class="content">
      <div class="content-con">
        <!-- 左侧 -->
        <div class="left-body">
          <div class="left-top public-bg">
            <div class="public-title">养殖池信息</div>
            <div class="tank-info" v-if="selectedTank">
              <p><b>编号：</b>{{ selectedTank.tankCode }}</p>
              <p><b>区域：</b>{{ selectedTank.areaName }}</p>
              <p><b>状态：</b>{{ selectedTank.status }}</p>
              <p v-if="selectedTank.species">
                <b>养殖生物：</b>{{ selectedTank.species.speciesName }}
                <img
                  :src="getFullUrl(selectedTank.species?.photoUrl)"
                  class="species-img"
                  alt="物种图"
                />
              </p>
              <p><b>适宜水温：</b>{{ selectedTank.species?.minTemp }} - {{ selectedTank.species?.maxTemp }} ℃</p>
              <p><b>溶氧：</b>{{ selectedTank.species?.minAmmonia }} - {{ selectedTank.species?.maxAmmonia }} mg/L</p>
              <p><b>投喂频率：</b>{{ selectedTank.species?.feedingFreqAdult }}</p>
            </div>
            <!-- 不默认展示占位提示，保持与你第二张图一致的“空”视觉 -->
             <!-- 未选桶：显示汇总（上下排放） -->
            <div class="tank-summary" v-else v-loading="summaryLoading">
              <ul class="stat-list">
                <li class="stat-item">
                  <span class="label">区域总数</span>
                  <span class="value">{{ summary.areaTotal }}</span>
                </li>
                <li class="stat-item">
                  <span class="label">养殖桶总数</span>
                  <span class="value">{{ summary.tankTotal }}</span>
                </li>
                <li class="stat-item">
                  <span class="label">正在养殖</span>
                  <span class="value">{{ summary.breeding }}</span>
                </li>
                <li class="stat-item">
                  <span class="label">养殖完成</span>
                  <span class="value">{{ summary.breedingDone }}</span>
                </li>
                <li class="stat-item ok">
                  <span class="label">正常</span>
                  <span class="value">{{ summary.normal }}</span>
                </li>
                <li class="stat-item warn">
                  <span class="label">预警</span>
                  <span class="value">{{ summary.warning }}</span>
                </li>
                <li class="stat-item bad">
                  <span class="label">异常</span>
                  <span class="value">{{ summary.danger }}</span>
                </li>
              </ul>
            </div>
          </div>

          <div class="left-con public-bg">
            <div class="public-title">产量分布情况</div>
            <div class="title-nav" id="leida"></div>
          </div>

          <!-- 左下角：投喂记录（首屏不渲染图表，但容器已占位，避免布局跳变） -->
          <div class="left-bottom public-bg">
            <div class="public-title">投喂记录</div>
            <div class="title-nav">
              <div id="feedingChart" class="chart"></div>
            </div>
          </div>
        </div>

        <!-- 中间 -->
        <div class="center-body">
          <div class="area-wrapper">
            <div class="area-container" v-for="(tanks, area) in areaBuckets" :key="area">
              <h3>{{ area }}</h3>
              <div class="tank-list">
                <div
                  class="tank-item"
                  v-for="tank in tanks"
                  :key="tank.id"
                  @click="showTankInfo(tank)"
                >
                  <div class="tank-item-left">
                    <img class="tank-icon" :src="getTankIcon(tank.status)" />
                    <span class="tank-code">{{ tank.tankCode }}</span>
                  </div>
                  <div class="tank-item-right">{{ tank.status }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 中间下半部分：生长记录曲线（首屏不渲染图表，但容器已占位） -->
          <div class="center-bottom public-bg">
            <div class="public-title">生长记录曲线</div>
            <div class="title-nav">
              <div id="centerGrowthChart" class="chart"></div>
            </div>
          </div>
        </div>

        <!-- 右侧 -->
        <div class="right-body">
          <!-- <div class="right-top public-bg">
            <div class="public-title">养殖桶视频</div>
            <div class="title-nav video-wrap">
              <template v-if="videoUrl">
                <video
                  :key="videoUrl"
                  class="video"
                  :src="videoUrl"
                  controls
                  autoplay
                  muted
                  playsinline
                ></video>
              </template>
            </div>
          </div> -->
        <div class="right-top public-bg">
          <div class="public-title">监控视频</div>
            <div class="title-nav video-wrap">
              <video
                :src="tankVideoUrl"
                controls
                muted
                autoplay
                loop
                playsinline
                style="width:100%;height:100%;object-fit:cover;border-radius:6px;"
              ></video>
            </div>
          </div>

<!--          <div class="right-con public-bg">-->
<!--            <div class="public-title">销售记录-->
<!--              <el-dropdown @command="handleSalesCommand">-->
<!--                <el-button size="small" type="primary">-->
<!--                  时间范围-->
<!--                  <el-icon class="el-icon&#45;&#45;right">-->
<!--                    <arrow-down />-->
<!--                  </el-icon>-->
<!--                </el-button>-->
<!--                <template #dropdown>-->
<!--                  <el-dropdown-menu>-->
<!--                    <el-dropdown-item command="day">日</el-dropdown-item>-->
<!--                    <el-dropdown-item command="month">月</el-dropdown-item>-->
<!--                    <el-dropdown-item command="year">年</el-dropdown-item>-->
<!--                  </el-dropdown-menu>-->
<!--                </template>-->
<!--              </el-dropdown></div>-->
            <div class="title-nav" id="huaxing"></div>
<!--              <el-dropdown @command="handleSalesCommand">-->
<!--                <el-button size="small" type="primary">-->
<!--                  时间范围-->
<!--                  <el-icon class="el-icon&#45;&#45;right">-->
<!--                    <arrow-down />-->
<!--                  </el-icon>-->
<!--                </el-button>-->
<!--                <template #dropdown>-->
<!--                  <el-dropdown-menu>-->
<!--                    <el-dropdown-item command="day">日</el-dropdown-item>-->
<!--                    <el-dropdown-item command="month">月</el-dropdown-item>-->
<!--                    <el-dropdown-item command="year">年</el-dropdown-item>-->
<!--                  </el-dropdown-menu>-->
<!--                </template>-->
<!--              </el-dropdown>-->
<!--            </div>-->
            <div class="right-con public-bg">
              <div class="title-nav" id="huaxing"></div>
              <div class="public-title">销售记录
<!--                <el-dropdown @command="handleSalesCommand" style="float: right;">-->
<!--                  <el-button size="small" type="primary">-->
<!--                    时间范围-->
<!--                    <el-icon class="el-icon&#45;&#45;right">-->
<!--                      <arrow-down />-->
<!--                    </el-icon>-->
<!--                  </el-button>-->
<!--                  <template #dropdown>-->
<!--                    <el-dropdown-menu>-->
<!--&lt;!&ndash;                      <el-dropdown-item command="days">日期间隔</el-dropdown-item>&ndash;&gt;-->
<!--&lt;!&ndash;                      <el-dropdown-item command="day">日</el-dropdown-item>&ndash;&gt;-->
<!--&lt;!&ndash;                      <el-dropdown-item command="month">月</el-dropdown-item>&ndash;&gt;-->
<!--                      <el-dropdown-item command="year">年</el-dropdown-item>-->
<!--                    </el-dropdown-menu>-->
<!--                  </template>-->
<!--                </el-dropdown>-->
              </div>
              <div class="title-nav tank-summary">
                <ul class="stat-list">
                  <li class="stat-item">
                    <span class="label">订单总数</span>
                    <span class="value">{{ totalOrders }}</span>
                  </li>
                  <li class="stat-item">
                    <span class="label">订单总数</span>
                    <span class="value">{{ totalAmount }}</span>
                  </li>
                  <li class="stat-item">
                    <span class="label">平均订单金额</span>
                    <span class="value">{{ avgOrderValue }}</span>
                  </li>
                  <li class="stat-item">
                    <span class="label">产品名称</span>
                    <span class="value">{{ topProductName }}</span>
                  </li>
<!--                  <li class="stat-item ok">-->
<!--                    <span class="label">销售5</span>-->
<!--                    <span class="value">{{ totalQuantity }}</span>-->
<!--                  </li>-->
                </ul>
              </div>
            </div>
<!--          </div>-->
<!--            <ul class="stat-list">-->
<!--              <li-->
<!--                v-for="(item, index) in salesStats"-->
<!--                :key="index"-->
<!--                class="stat-item"-->
<!--                :class="item.type"-->
<!--              >-->
<!--                <div class="stat-item-content">-->
<!--                  <div class="stat-item-icon">-->
<!--                    &lt;!&ndash; 这可以添加图标 &ndash;&gt;-->
<!--                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">-->
<!--                      <path d="M12 2a1 1 0 011 1v1h2a2 2 0 012 2v2h1a2 2 0 012 2v5a3 3 0 01-3 3h-1.18a3 3 0 01-2.82 2h-4a3 3 0 01-3-3V10a2 2 0 012-2h1V6a2 2 0 012-2h2V3a1 1 0 011-1h2zM7 11.5a1.5 1.5 0 103 0 1.5 1.5 0 00-3 0zm7 0a1.5 1.5 0 103 0 1.5 1.5 0 00-3 0zM9 17h6a1 1 0 100-2H9a1 1 0 100 2z"/>-->
<!--                    </svg>-->
<!--                  </div>-->
<!--                  <span class="label">{{ item.label }}</span>-->
<!--                  <span class="value">{{ item.value }}</span>-->
<!--                </div>-->
<!--              </li>-->
<!--            </ul>-->
<!--          </div>-->
<!--          </div>-->


          <div class="right-bottom public-bg">
            <div class="public-title">桶状态展示</div>
            <div class="title-nav tank-status-scroll">
              <div class="top5-ul">
                <ul>
                  <li v-for="(tank, index) in sortedTanks" :key="tank.id">
                    <span class="rank">{{ index + 1 }}</span>
                    <span class="status" :class="getStatusClass(tank.status)">{{ tank.status }}</span>
                    <span class="area">{{ tank.areaName || "未知区域" }}</span>
                    <span class="code">{{ tank.tankCode }}</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>

          <!-- 右侧第三块保留给后续扩展（如折线图），当前按两块布局显示 -->
        </div>
      </div>
    </div>
  </div>
  <div class="ai-mask" v-show="aiOpen" @click="aiOpen=false"></div>
    <aside class="ai-drawer" :class="{ open: aiOpen }">
    <div class="ai-drawer__header">
      <span>AI 助手</span>
      <button class="ai-close" @click="aiOpen=false">×</button>
    </div>
    <iframe
      src="http://120.46.208.199:9306/zh"
      allow="microphone; clipboard-read; clipboard-write"
      referrerpolicy="no-referrer"
    ></iframe>
  </aside>
</div>
</template>

<script setup>
import * as echarts from "echarts"
import { initCharts } from "@/dashboard/index.js"
import { listSysTanks } from "@/api/SysTanks/SysTanks"
import { ref,reactive, computed, onMounted, onUnmounted, nextTick, watch } from "vue"
import greenIcon from "@/assets/icons/green.png"
import yellowIcon from "@/assets/icons/yellow.png"
import redIcon from "@/assets/icons/red.png"
import nullIcon from "@/assets/icons/null.png"
import { useRouter } from "vue-router"
import { getSysTanks } from "@/api/SysTanks/SysTanks"
import { getSysAquaticSpecies } from "@/api/SysAquaticSpecies/SysAquaticSpecies"
import { listSysGrowthRecords } from "@/api/SysGrowthRecords/SysGrowthRecords"
import { listSysFeedingRecords } from "@/api/SysFeedingRecords/SysFeedingRecords"
import tankVideoUrl from '@/assets/images/video.mp4'
import { listStatistics } from '@/api/dashboard/dashboard.js'
import { getSalesStat } from '@/api/dashboard/dashboard.js'
import {ArrowDown} from "@element-plus/icons-vue";

// 添加以下代码来处理 devtools 兼容性问题
if (typeof window !== 'undefined' && window.__VUE_DEVTOOLS_GLOBAL_HOOK__) {
  // 防止 devtools 报错
  console.warn('Vue DevTools 兼容性警告已处理')
}

const selectedTank = ref(null)
const videoUrl = ref('')
const aiOpen = ref(false)
// const totalOrders = ref(0)
// const totalAmount = ref(0)
// const avgOrderValue = ref(0)
// const topProductName = ref('')
// const totalQuantity = ref(0)
watch(aiOpen, async () => {
  // 给 ECharts 一个重算机会，避免抽屉展开后图表尺寸不对
  await nextTick()
  requestAnimationFrame(() => {
    window.dispatchEvent(new Event('resize'))
  })
})
// 死数据（需要时直接改数字即可）
// 汇总数据（未选桶时展示）
const summary = reactive({
  areaTotal: 0,
  tankTotal: 0,
  breeding: 0,
  breedingDone: 0,   // -> 对应后端的 breedingDone
  normal: 0,
  warning: 0,
  danger: 0,   // -> 对应后端的 danger
})

const summaryLoading = ref(false)

async function fetchSummary() {
  summaryLoading.value = true
  try {
    const res = await listStatistics()
    const d = res?.data || {}
    console.log('统计接口返回数据:', res.data)
    summary.areaTotal = d.areaTotal ?? 0
    summary.tankTotal = d.tankTotal ?? 0
    summary.breeding  = d.breeding ?? 0
    summary.breedingDone  = d.breedingDone ?? 0   // 映射：finished <- breedingDone
    summary.normal    = d.normal ?? 0
    summary.warning   = d.warning ?? 0
    summary.danger  = d.danger ?? 0         // 映射：abnormal <- danger
  } catch (e) {
    console.error('统计接口出错:', e)
  } finally {
    summaryLoading.value = false
  }
}

// ====== 死数据：未选中任何桶时用于占位展示 ======
const DEFAULT_GROWTH = [
  { recordDate: '2025-09-01', avgLength: 3.2, avgWeight: 1.4 },
  { recordDate: '2025-09-04', avgLength: 3.6, avgWeight: 1.7 },
  { recordDate: '2025-09-07', avgLength: 4.1, avgWeight: 2.1 },
  { recordDate: '2025-09-10', avgLength: 4.6, avgWeight: 2.6 },
  { recordDate: '2025-09-13', avgLength: 5.0, avgWeight: 3.0 },
  { recordDate: '2025-09-15', avgLength: 5.3, avgWeight: 3.3 }
]

const DEFAULT_FEEDING = [
  { feedTime: '2025-09-01 08:00', feedAmount: 12, remainRate: 8 },
  { feedTime: '2025-09-03 08:00', feedAmount: 14, remainRate: 10 },
  { feedTime: '2025-09-06 08:00', feedAmount: 15, remainRate: 7 },
  { feedTime: '2025-09-09 08:00', feedAmount: 16, remainRate: 6 },
  { feedTime: '2025-09-12 08:00', feedAmount: 18, remainRate: 5 },
  { feedTime: '2025-09-15 08:00', feedAmount: 20, remainRate: 4 }
]


// 获取图片的完整URL
function getFullUrl(path) {
  if (!path) return ""
  return path.startsWith("http") ? path : `http://localhost:8080${path}`
}

let centerGrowthChart = null
let feedingChart = null

async function showTankInfo(tank) {
  // 查桶详情
  const res = await getSysTanks(tank.id)
  selectedTank.value = res.data

  // 如果桶里有 speciesId，再查生物信息
  if (res.data.speciesId) {
    const speciesRes = await getSysAquaticSpecies(res.data.speciesId)
    selectedTank.value.species = speciesRes.data
  }

  // 查生长记录
  const growthRes = await listSysGrowthRecords({ tankId: tank.id })
  if (growthRes.rows?.length) {
    renderGrowthChart(growthRes.rows)
  } else {
    // 无数据也清掉旧图，保持空容器（不影响布局）
    // if (centerGrowthChart) {
    //   centerGrowthChart.dispose()
    //   centerGrowthChart = null
    // }
    renderGrowthChart(DEFAULT_GROWTH) // 无数据时用死数据占位
  }

  // 查投喂记录
  const feedRes = await listSysFeedingRecords({ tankId: tank.id, pageNum: 1, pageSize: 20 })
  if (feedRes.rows?.length) {
    renderFeedingChart(feedRes.rows)
  } else {
    // if (feedingChart) {
    //   feedingChart.dispose()
    //   feedingChart = null
    // }
    renderFeedingChart(DEFAULT_FEEDING) // 无数据时用死数据占位
  }

   // === 新增：设置视频地址（后端字段举例 videoUrl/streamUrl，按你真实字段改） ===
  // === 设置视频地址（后端字段：vedioUrl） ===
    const rawUrl = res.data.videoUrl || '';
    videoUrl.value = rawUrl ? getFullUrl(rawUrl) : '';

  // 选择后下一帧做一次自适应，确保尺寸正确
  requestAnimationFrame(() => {
    feedingChart?.resize()
    centerGrowthChart?.resize()
  })
}

// 渲染生长记录变化图
function renderGrowthChart(records) {
  nextTick(() => {
    const chartDom = document.getElementById("centerGrowthChart")
    if (!chartDom) return
    if (centerGrowthChart) centerGrowthChart.dispose()
    centerGrowthChart = echarts.init(chartDom)

    const dates = records.map(r => r.recordDate)
    const lengths = records.map(r => r.avgLength || 0)
    const weights = records.map(r => r.avgWeight || 0)

    const option = {
      tooltip: { trigger: "axis" },
      legend: { data: ["体长", "体重"], textStyle: { color: "#fff" } },
      grid: { left: "5%", right: "5%", bottom: "10%", containLabel: true },
      xAxis: { type: "category", data: dates, axisLine: { lineStyle: { color: "#ccc" } } },
      yAxis: { type: "value", axisLine: { lineStyle: { color: "#ccc" } } },
      series: [
        { name: "体长", type: "line", smooth: true, data: lengths },
        { name: "体重", type: "line", smooth: true, data: weights }
      ]
    }

    centerGrowthChart.setOption(option)
  })
}

// 渲染投喂记录双轴图
function renderFeedingChart(records) {
  nextTick(() => {
    const chartDom = document.getElementById("feedingChart")
    if (!chartDom) return
    if (feedingChart) feedingChart.dispose()
    feedingChart = echarts.init(chartDom)

    const dates = records.map(r => r.feedTime)
    const feedAmounts = records.map(r => r.feedAmount || 0)
    const remainRates = records.map(r => r.remainRate || 0)

    const option = {
      tooltip: { trigger: "axis" },
      legend: { data: ["投喂量", "残饵率"], textStyle: { color: "#fff" } },
      grid: { left: "8%", right: "8%", bottom: "10%", containLabel: true },
      xAxis: {
        type: "category",
        data: dates,
        axisLine: { lineStyle: { color: "#ccc" } }
      },
      yAxis: [
        {
          type: "value",
          name: "投喂量",
          position: "left",
          axisLine: { lineStyle: { color: "#1890ff" } },
          axisLabel: { formatter: "{value}" }
        },
        {
          type: "value",
          name: "残饵率",
          position: "right",
          axisLine: { lineStyle: { color: "#f5222d" } },
          axisLabel: { formatter: "{value}%" }
        }
      ],
      series: [
        {
          name: "投喂量",
          type: "bar",
          data: feedAmounts,
          yAxisIndex: 0,
          itemStyle: { color: "#1890ff" }
        },
        {
          name: "残饵率",
          type: "line",
          smooth: true,
          data: remainRates,
          yAxisIndex: 1,
          itemStyle: { color: "#f5222d" }
        }
      ]
    }

    feedingChart.setOption(option)
  })
}

// 桶状态优先级：异常 > 预警 > 繁殖 > 正常 > 空桶
const statusOrder = { "异常": 1, "预警": 2, "繁殖": 3, "正常": 4, "空桶": 5 }

const SysTanksList = ref([])

const sortedTanks = computed(() => {
  return [...SysTanksList.value].sort((a, b) => {
    return (statusOrder[a.status] || 99) - (statusOrder[b.status] || 99)
  })
})

// 状态对应的样式
function getStatusClass(status) {
  const s = (status || "").trim()
  switch (s) {
    case "异常": return "status-error"
    case "预警": return "status-warning"
    // case "繁殖": return "status-breed"
    case "正常": return "status-normal"
    case "空桶": return "status-empty"
    default: return ""
  }
}

const router = useRouter()
function goSysTanks() {
  router.push("/SysTanks")
}

// 根据状态获取对应的图标
function getTankIcon(status) {
  switch (status) {
    case "正常":  return greenIcon
    case "预警":  return yellowIcon
    case "异常":  return redIcon
    case "空桶":  return nullIcon
    default:       return nullIcon
  }
}

// 获取桶数据
function getTanks() {
  listSysTanks({ pageNum: 1, pageSize: 1000 }).then(res => {
    SysTanksList.value = res.rows || []
  })
}

// 计算分组：区域 -> 桶数组
const areaBuckets = computed(() => {
  const groups = {}
  SysTanksList.value.forEach(tank => {
    if (!groups[tank.areaName]) groups[tank.areaName] = []
    groups[tank.areaName].push(tank)
  })
  return groups
})

// 实时时间
const time = ref("")
function fillZero(str) {
  return str < 10 ? "0" + str : str
}
function getTime() {
  const myDate = new Date()
  const myYear = myDate.getFullYear()
  const myMonth = myDate.getMonth() + 1
  const myToday = myDate.getDate()
  const myDay = myDate.getDay()
  const myHour = myDate.getHours()
  const myMinute = myDate.getMinutes()
  const mySecond = myDate.getSeconds()
  const week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
  time.value =
    myYear + "年" + fillZero(myMonth) + "月" + fillZero(myToday) + "日 " +
    fillZero(myHour) + ":" + fillZero(myMinute) + ":" + fillZero(mySecond) + " " +
    week[myDay]
}

let timer = null

onMounted(async () => {
  getTime()
  timer = setInterval(getTime, 1000)

  // 等待 Grid/CSS 全挂到 DOM，再初始化雷达/环图
  await nextTick()
  initCharts()   // 仅初始化首屏静态图（雷达、环图）

  // ① 首屏：用死数据渲染“生长记录曲线/投喂记录”
  renderGrowthChart(DEFAULT_GROWTH)
  renderFeedingChart(DEFAULT_FEEDING)

  // 拉取桶数据（渲染中间区域列表）
  getTanks()

  // 首屏强制一次自适应，确保静态图尺寸正确
  requestAnimationFrame(() => {
    window.dispatchEvent(new Event("resize"))
  })
  await fetchSummary()
  await getSalesStat({yearFlag: true}).then(response =>{
    console.log('response', response)
    totalOrders.value = response.totalOrders
    totalAmount.value = response.totalAmount
    avgOrderValue.value = response.avgOrderValue
    topProductName.value = response.topProductName
    console.log('totalOrders', totalOrders.value)
  }) // 默认加载年数据
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})

// 在 setup 函数中定义响应式变量，确保它们在组件初始化前就存在
const totalOrders = ref(0)
const totalAmount = ref(0)
const avgOrderValue = ref(0)
const topProductName = ref('')
const totalQuantity = ref(0)
// const daterangePeriodDate = ref([])
// 确保在使用这些变量前已经定义好
function handleSalesCommand(command) {
  console.log('处理销售数据', command)

  // 清空现有数据
  totalOrders.value = 0
  totalAmount.value = 0
  avgOrderValue.value = 0
  topProductName.value = ''
  totalQuantity.value = 0

  let params = {};
  if (command === 'days') {
    // 日期间隔：传递 beginTime 和 endTime
    if (daterangePeriodDate.value && daterangePeriodDate.value.length === 2) {
      params = {
        beginTime: `${daterangePeriodDate.value[0]} 00:00:00`,
        endTime: `${daterangePeriodDate.value[1]} 23:59:59`
      };
    }
  } else {
    // 日/月/年：传递对应的 flag
    params = { [command + 'Flag']: true };
  }

  getSalesStat(params).then(res => {
    console.log('接口返回结果:', res)
    const data = res || {}
    console.log('销售数据:', data)
    data.totalQuantity = res.totalQuantity || 0;
    data.topProductName = res.topProductName || '';

    // 统一处理数据并更新响应式变量
    totalOrders.value = data.totalOrders || 0
    totalAmount.value = data.totalAmount || 0
    avgOrderValue.value = data.avgOrderValue || 0
    topProductName.value = data.topProductName || ''
    totalQuantity.value = data.totalQuantity || 0

    // 添加调试信息
    console.log('更新后的数据:', {
      totalOrders: totalOrders.value,
      totalAmount: totalAmount.value,
      avgOrderValue: avgOrderValue.value,
      topProductName: topProductName.value,
      totalQuantity: totalQuantity.value
    })
  }).catch(error => {
    console.error('获取销售数据失败:', error)
  })
}


</script>

<style scoped>
/* 主体容器：默认100%，打开AI时收缩 */
.main-wrap{ width: 100%; }
.ai-mask{
  position: fixed; inset: 0;
  background: rgba(0,0,0,.35);
  z-index: 999;                 /* 小于抽屉，大于大屏 */
}
/* 右侧抽屉本体 */
.ai-drawer{
  position: fixed; top: 0; right: 0;
  width: var(--ai-width); height: 100vh;
  background: #0b1730;
  border-left: 1px solid rgba(255,255,255,.08);
  display: flex; flex-direction: column;
  transform: translateX(100%);  /* 默认隐藏在右外侧 */
  transition: transform .35s ease;
  z-index: 1000;                /* 盖住大屏 */
  pointer-events: none;         /* 关闭时不拦截点击 */
}
.ai-drawer.open{
  transform: translateX(0);
  pointer-events: auto;         /* 打开后可交互 */
}
.ai-close{
  border:0; background:transparent; color:#7aa2ff; font-size:20px; cursor:pointer;
}
.ai-drawer__header{
  height: 44px; display:flex; align-items:center; justify-content:space-between;
  padding: 0 12px; color:#cfe7ff;
  border-bottom: 1px solid rgba(255,255,255,.08);
}
.ai-drawer iframe{
  flex: 1 1 auto;
  width: 100%;
  height: calc(100% - 44px);
  border: none;
}

/* ===== 页面骨架（不依赖任何全局样式） ===== */
.content-body{
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #254e7c;
  background : linear-gradient(135deg, #0b1730 0%, #4694ec 100%);
  position: relative;
  overflow: hidden;
  --ai-width: 420px; /* 自己改宽度 */
}
.header{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
}
.header-left{ flex: 1; }
.header-title{
  flex: 1;
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  color: #fff;
}
.header-time{
  flex: 1;
  text-align: right;
  font-size: 16px;
  color: #fff;
  display:flex; align-items:center; gap:10px; justify-content:flex-end;
}
.ai-btn{
  width:30px;height:30px;border-radius:50%;
  display:inline-flex;align-items:center;justify-content:center;
  background:rgba(255,255,255,.1); color:#9fc6ff; border:1px solid rgba(255,255,255,.15);
  cursor:pointer; transition:all .2s ease;
}
.ai-btn:hover{ background:rgba(255,255,255,.18); color:#cfe7ff; }
/* 小屏自适应：抽屉宽度缩小或全屏 */
@media (max-width: 1400px){
  .content-body{ --ai-width: 420px; }
}
@media (max-width: 992px){
  .content-body{ --ai-width: 100vw; } /* 手机端全屏抽屉 */
}
.content{
  flex: 1 1 auto;
  min-height: 0;
  padding: 0 12px 12px;
}

/* ===== 三列三行网格：轨道固定，首屏与点击后布局一致 ===== */
.content .content-con{
  height: 100%;
  display: grid;
  grid-template-columns: 22% 1fr 22%;
  grid-template-rows: repeat(3, 250px); /* 三行都 250px */
  gap: 16px;
}


/* 让列容器把子块直接“透传”到网格里 */
.left-body, .center-body, .right-body{ display: contents; }

/* 左列三块 */
.left-top    { grid-column: 1; grid-row: 1; }
.left-con    { grid-column: 1; grid-row: 2; }
.left-bottom { grid-column: 1; grid-row: 3; }

/* 中列：上部跨两行；下部一行 */
.area-wrapper  { grid-column: 2; grid-row: 1 / span 2; min-height: 0; overflow: auto; }
.center-bottom { grid-column: 2; grid-row: 3; min-height: 0; }

/* 右列两块（占第2、3行） */
.right-top    { grid-column: 3; grid-row: 1; min-height: 0; }
.right-con    { grid-column: 3; grid-row: 2; min-height: 0; }
.right-bottom { grid-column: 3; grid-row: 3; min-height: 0; }

/* ===== 卡片通用样式 ===== */
.public-bg{
  background: rgba(255,255,255,0.06);
  border: 1px solid rgba(255,255,255,0.08);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}
.public-title{
  flex: 0 0 30px;
  height: 30px;
  line-height: 30px;
  padding: 0 12px;
  color: #cfe7ff;
  border-bottom: 1px solid rgba(255,255,255,0.08);
}
.title-nav{
  flex: 1 1 auto;
  min-height: 0;
  padding: 8px 12px;
  display: flex;
  align-items: stretch;
}

/* 图表容器（首屏也占位，防止点击后布局变化） */
.chart{ width: 100%; height: 100%; }

/* ===== 左列细节 ===== */
.tank-info{
  max-height: 230px;
  overflow: auto;
  padding: 8px 12px;
  color: #fff;
  font-size: 14px;
}
.species-img{
  width: 80px; height: 80px; object-fit: cover;
  border-radius: 6px; margin-top: 8px;
}

/* ===== 中列：区域与桶列表 ===== */
.area-container{
  flex: 1 1 300px;
  border: 1px solid #3a8ee6;
  border-radius: 6px;
  padding: 10px;
  background: rgba(0,0,0,0.18);
  color: #e7f1ff;
  margin-bottom: 12px;
}
.area-container h3{
  margin: 0;
  font-size: 16px;
  color: #9fc6ff;
}
.tank-list{ margin-top: 10px; }
.tank-item{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 4px 0;
  padding: 6px 8px;
  border-radius: 4px;
  background: rgba(255,255,255,0.08);
  color: #e7f1ff;
  cursor: pointer;
  transition: background .2s ease;
}
.tank-item:hover{ background: rgba(255,255,255,0.16); }
.tank-item-left{ display: inline-flex; align-items: center; gap: 8px; }
.tank-item-right{ font-size: 12px; opacity: .85; }
.tank-icon{ width: 22px; height: 22px; }
.tank-code{ font-size: 14px; }

/* ===== 右列：状态列表 ===== */
.tank-status-scroll{ overflow: auto; padding-right: 6px; }
.top5-ul ul{ list-style: none; margin: 0; padding: 0; }
.top5-ul li{
  display: grid;
  grid-template-columns: 36px 80px 100px 100px; /* 序号 / 状态 / 区域(自适应) / 桶编号 */
  gap: 8px;
  align-items: center;
  padding: 6px 0;
  font-size: 14px;
  color: #fff;
  border-bottom: 1px solid rgba(255,255,255,0.1);
}
.top5-ul li .rank{text-align: center; font-weight: bold; }
.top5-ul li .status{
text-align: center; color: #fff;
  border-radius: 4px; padding: 2px 6px; font-weight: bold;
}

.stat-item .value {
  color: #ffffff;
  font-weight: 700;
  font-size: 18px;
}

.stat-item.ok .value {
  color: #39d98a;
}

.stat-item.warn .value {
  color: #ffb020;
}

.stat-item.bad .value {
  color: #ff5d5d;
}

/* 状态颜色 */
.status-error   { background-color: #ff4d4f !important; }
.status-warning { background-color: #faad14 !important; }
.status-breed   { background-color: #eb2f96 !important; }
.status-normal  { background-color: #52c41a !important; }
.status-empty   { background-color: #595959 !important; }

/* ===== 让第二行的图表区域在卡片中铺满 ===== */
.left-con .title-nav,
.right-con .title-nav,
.center-bottom .title-nav{
  display: flex;
  align-items: stretch;
  justify-content: stretch;
  min-height: 0;
}

/* 保证“投喂记录/生长曲线”首屏即有固定高度（不跳变） */
.left-bottom .title-nav,
.center-bottom .title-nav{
  height: calc(100% - 0px); /* 已由 flex 分配高度，这里确保铺满 */
}

.tank-summary { padding: 10px 12px; min-height: 0; overflow: auto;}
.stat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.stat-item { display: flex; justify-content: space-between; align-items: center; background: rgba(255,255,255,0.04); border-radius: 8px; padding: 8px 10px; }
.stat-item .label { color: #bfc7d5; font-size: 13px; }
.stat-item .value { color: #ffffff; font-weight: 700; font-size: 18px; }
.stat-item.ok   .value { color: #39d98a; }
.stat-item.warn .value { color: #ffb020; }
.stat-item.bad  .value { color: #ff5d5d; }
/* ===== 左侧：养殖桶信息 ===== */
.tank-summary {
  padding: 10px 12px;
  min-height: 0;
  overflow: auto;
}

.stat-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255,255,255,0.04);
  border-radius: 8px;
  padding: 8px 10px;
}

.stat-item .label {
  color: #bfc7d5;
  font-size: 13px;
}

.stat-item .value {
  color: #ffffff;
  font-weight: 700;
  font-size: 18px;
}

.stat-item.ok .value {
  color: #39d98a;
}

.stat-item.warn .value {
  color: #ffb020;
}

.stat-item.bad .value {
  color: #ff5d5d;
}

/* ===== 右列：状态list ===== */
.sales-scroll {
  overflow-y: auto;
  max-height: 200px;
  padding-right: 6px;
}

.stat-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction:column;
  gap: 8px;
  width: 100%; /* 设置列表宽度为100% */
}

.stat-item {
  display:flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255,255,255,0.04);
  border-radius: 8px;
  padding: 8px 10px;
  width: 100%; /* 设置列表项宽度为100% */
}

.stat-item .label {
  color: #bfc7d5;
  font-size: 13px;
}

.stat-item .value {
  color: #ffffff;
  font-weight: 700;
  font-size: 18px;
}

.stat-item.ok .value {
  color: #39r98a;
}

.stat-item.warn .value {
  color: #ffb020;
}

.stat-item.bad .value {
  color: #ff5d5d;
}


</style>